import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  LoggerService,
  Inject,
} from '@nestjs/common'

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @Inject('WINSTON_LOGGER') private readonly logger: LoggerService,
  ) {}
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const request = ctx.getRequest()

    // 获取异常状态码
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR

    // 获取异常信息
    let message = exception.message || '服务器内部错误'
    if (exception.response && exception.response.message) {
      message = Array.isArray(exception.response.message)
        ? exception.response.message.join(', ')
        : exception.response.message
    }
    this.logger.error(message, exception.stack)

    // 构建响应体
    const responseBody = {
      data: null,
      code: status,
      message: message,
      path: request.url,
      timestamp: new Date().toISOString(),
    }

    // 记录错误日志
    console.error(`异常信息: ${exception.message}`)
    console.error(`异常堆栈: ${exception.stack}`)

    // 发送响应
    response.status(status).json(responseBody)
  }
}
